<script lang="ts" setup>
import type { RowType } from '../../types';

import { useVbenModal } from '@vben/common-ui';

import { Button, Input, InputGroup, message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { postRoutes, putRoutes } from '#/api/admin/routes';

import TableModalView from './TableModal.vue';

const [Form, formApi] = useVbenForm({
  handleSubmit: onSubmit,
  schema: [
    {
      component: 'Input',
      dependencies: {
        show: false,
        // 随意一个字段改变时，都会触发
        triggerFields: ['id'],
      },
      fieldName: 'id',
      label: 'ID',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'full_url',
      label: '原始网址',
      rules: 'required',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'url',
      label: '显示网址',
      rules: 'required',
    },
    {
      component: 'Switch',
      componentProps: {
        checkedValue: 1,
        unCheckedValue: 0,
        checkedChildren: '启用',
        unCheckedChildren: '停用',
      },
      fieldName: 'status',
      label: '状态',
    },
  ],
  showDefaultActions: false,
});
const [Modal, formModalApi] = useVbenModal({
  fullscreenButton: false,
  onCancel() {
    formModalApi.close();
  },
  onConfirm: async () => {
    await formApi.validateAndSubmitForm();
    formModalApi.close();
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const values: RowType = formModalApi.getData();
      if (values) {
        formApi.setValues(values);
      }
    }
  },
});

async function onSubmit(values: any) {
  function showMsg(msg: string) {
    message.success(msg);
    formModalApi.setData({ isUpdata: true });
  }
  if (values.id) {
    const { msg } = await putRoutes(values.id, values);
    showMsg(msg);
  } else {
    const { msg } = await postRoutes(values);
    showMsg(msg);
  }
}

const [TableModal, tableModalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: TableModalView,
  onClosed() {
    const tableModalData = tableModalApi.getData();
    if (tableModalData) {
      const newForm: any = {};
      if (typeof tableModalData === 'string') {
        newForm.full_url = tableModalData;
        return;
      }
      newForm.full_url = tableModalData.key;
      newForm.url = tableModalData.suggest_url;
      formApi.setValues(newForm);
    }
  },
});

const openMoreDialog = (title: string = '选择规则') => {
  tableModalApi.setState({
    title,
  });
  tableModalApi.open();
};
</script>
<template>
  <Modal class="w-3/5">
    <TableModal />
    <Form>
      <template #full_url="slotProps">
        <InputGroup compact>
          <Input v-bind="slotProps" style="width: calc(100% - 100px)" />
          <Button type="primary" @click="openMoreDialog()">选择规则</Button>
        </InputGroup>
      </template>
    </Form>
  </Modal>
</template>

<style lang="scss" scoped></style>
